package com.lxq.market.service;

import com.lxq.market.model.App;
import com.lxq.market.util.JDBCUtil;
import com.lxq.market.util.ResultSetConvert;

import java.util.List;
import java.util.stream.Collectors;

public class AppService {

    private static AppService appService;
    ResultSetConvert resultSetConvert=ResultSetConvert.getInstance();

    public static AppService getInstance() {
        if (appService==null)appService=new AppService();
        return appService;
    }

    private AppService(){}

    public List<App> findAll(){
        return resultSetConvert.convert(JDBCUtil.execQuery("select * from app"), App.class);
    }

    public App findByAppName(String appName){
        return resultSetConvert.convertOne(JDBCUtil.execQuery("select * from app where app_name=?", appName), App.class);
    }

    public List<App> FindAllByStatueFilter(){
        return findAll().stream().filter(app -> !app.getAppState().equals("审核中")&&!app.getAppState().equals("下架")&&
                !app.getAppState().equals("删除")).collect(Collectors.toList());
    }

    public List<App> findAllByCategory(String category){
        return findAll().stream().filter(app -> !app.getAppState().equals("审核中") && !app.getAppState().equals("下架")&&
                        !app.getAppState().equals("删除"))
                .filter(app -> app.getAppCategory().equals(category)).collect(Collectors.toList());
    }

    public List<App> FindAllByUserId(String userId){
        return findAll().stream().filter(app -> app.getAppFrom().equals(userId)).collect(Collectors.toList());
    }

    public boolean addApp(App app){
        return JDBCUtil.execSQL("insert into app(app_name,app_id,app_from,app_ver,app_size,app_logo,app_score,app_shot," +
                        "app_description,app_state,app_file,app_category)"+
                " values(?,?,?,?,?,?,?,?,?,?,?,?)",
                app.getAppName(), app.getAppId(), app.getAppFrom(), app.getAppVer(), app.getAppSize(), app.getAppLogo(),
                5, app.getAppShot(), app.getAppDesc(), app.getAppState(),app.getAppFile(),app.getAppCategory());
    }

    public boolean changeAppState(String appName,String state){
        if(state.equals("删除")){
            return JDBCUtil.execSQL("delete from app where app_name=?", appName);
        }
        return JDBCUtil.execSQL("update app set app_state=? where app_name=?", state, appName);
    }
    public boolean changeAppCategory(String appName,String category){
        return JDBCUtil.execSQL("update app set app_category=? where app_name=?", category, appName);
    }
}
